package org.subatu.orm.service.base;

import org.subatu.orm.query.base.SqlData;
import org.subatu.orm.query.table.CondColumn;
import org.subatu.orm.util.SqlUtil;

import java.util.List;

public interface BaseQuery {

    // 查询的泛型类型
    Class<?> getResultType();

    SqlData sqlData();

    default String buildFromSql() {
        Class<?> clazz = getResultType();
        String tableName = SqlUtil.getTableName(clazz);
        return " from " + tableName + " ";
    }

    // 过滤 条件集合sql
    static String filterCondSql(String whereSql) {
        if (whereSql.startsWith("and ")) {
            whereSql = whereSql.substring(4);
        }
        if (whereSql.startsWith("or ")) {
            whereSql = whereSql.substring(3);
        }
        whereSql = whereSql.replace("where or", "where");
        whereSql = whereSql.replace("( and", "(");
        whereSql = whereSql.replace("( or", "(");
        whereSql = whereSql.replace("and and", "and");
        whereSql = whereSql.replace("and or", "and");
        whereSql = whereSql.replace("or and", "or");
        whereSql = whereSql.replace("or or", "or");
        return whereSql;
    }

    default String getAllCondSql(List<CondColumn> condColumnList) {
        String allCondSql = "";
        for (CondColumn condColumn : condColumnList) {
            String sql = condColumn.buildCondSql(this.sqlData().tableAliasMap, sqlData().valueList);
            allCondSql += sql;
        }
        // 过滤 条件sql
        allCondSql = filterCondSql(allCondSql);
        return allCondSql;
    }


    // 拼接 最后的sql
    default BaseQuery last(String sql) {
        sqlData().lastSql.append(sql);
        return this;
    }

    <T> List<T> list();

    <T> T one();

    <T> T one(boolean strict);


}
